package com.gimi.cloud.jimi.client.service.moreInfo.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.client.service.moreInfo.GongjijingService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.mq.service.MqCommonSenderService;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.common.mq.enume.QueueEnum;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.FengchaoGongjijinRegionDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.dto.app.moreInfo.GongjijingDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.FengchaoGongjijinRegionEntity;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.user.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther loongs
 * @date 2018/1/10  17:19
 */
@Service
public class GongjijingServiceImpl implements GongjijingService {
    private static Logger log = LoggerFactory.getLogger(GongjijingServiceImpl.class);

    private MoreInfoDao moreInfoDao;
    private SysConfigDao sysConfigDao;
    private InterfacePlatformRequestService requestService;
    private UserDao userDao;
    private IRedisService iRedisService;
    private FengchaoGongjijinRegionDao fengchaoGongjijinRegionDao;
    private MqCommonSenderService commonSenderService;

    private final Integer MAXTIMES = 3;
    private final String INTERFACE_PLATFORM_UNIVERSAL_GETPROVIDENTFUNDINFO="interface_platform_universal_getProvidentFundInfo";
    @Autowired
    public GongjijingServiceImpl(MoreInfoDao moreInfoDao, SysConfigDao sysConfigDao, InterfacePlatformRequestService requestService, UserDao userDao,
                                 IRedisService iRedisService, FengchaoGongjijinRegionDao fengchaoGongjijinRegionDao,MqCommonSenderService commonSenderService) {
        this.moreInfoDao = moreInfoDao;
        this.sysConfigDao = sysConfigDao;
        this.requestService = requestService;
        this.userDao = userDao;
        this.iRedisService=iRedisService;
        this.fengchaoGongjijinRegionDao=fengchaoGongjijinRegionDao;
        this.commonSenderService=commonSenderService;
    }

    @Override
    public List<FengchaoGongjijinRegionEntity> getProvidentFundInfoSupportedCityList(GongjijingDTO gongjijingDTO) {
        return fengchaoGongjijinRegionDao.selectAll();
    }

    @Override
    public FengchaoGongjijinRegionEntity getProvidentFundInfoCityLoginParameter(GongjijingDTO gongjijingDTO) {
        return fengchaoGongjijinRegionDao.selectByPrimaryKey(gongjijingDTO.getRegionId());
    }

    @Override
    public Response getProvidentFundInfoImage(GongjijingDTO gongjijingDTO) throws Exception {
        Response response =new Response();
        Map<String, Object> data = new HashMap<>();
        String fengchao_gongjijing = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_GETPROVIDENTFUNDINFO);
        JSONObject fgJson = JSON.parseObject(fengchao_gongjijing);
        JSONObject getverificationcodeimage = fgJson.getJSONObject("fengchao_gongjijin_getverificationcodeimage");
        JSONObject body = getverificationcodeimage.getJSONObject("body");
        body.put("location_cid", gongjijingDTO.getRegionCityId());
        getverificationcodeimage.put("body", body);
        String sendApiPost = requestService.sendApiPost(getverificationcodeimage.toJSONString());
        JSONObject parseObject = JSON.parseObject(sendApiPost);
        JSONObject returnBody = parseObject.getJSONObject("body");
        if(returnBody == null ){
            throw new MsgException(ResponseCodeEnum.INTERFACE_ERROR,"解析接口出错或者超时，请稍后再试！");
        }
        String status=returnBody.getString("status");
        if(!"1".equals(status) ){
            throw new MsgException(ResponseCodeEnum.INTERFACE_ERROR,"返回码不正确，请稍后再试！");
        }
        data.put("codeImage", returnBody);

        response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        response.setRes_data(data);
        return response;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public Response getProvidentFundInfo(GongjijingDTO gongjijingDTO) throws Exception {
        Response response = new Response();
        User user = userDao.getUserByUserId(gongjijingDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过社保信息
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndType(gongjijingDTO.getUserId(),6);

        //半段是不是新增，true是新增，false已存在
        boolean flag = false;
        //返回值为2的时候，是代表时间已经过期
        if (moreInfoEntity != null && (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 2 ||
                (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 0 && !"2".equals(moreInfoEntity.getGetdata())))) {
            //如果是有效期内，就做修改，不做新增
            //如果是失败的且过期时间为空，就需要做修改，不做新增
        }else {
            //时间过期了的新增
            moreInfoEntity = new MoreInfoEntity();
            moreInfoEntity.setGetdataTime(new Date());
            moreInfoEntity.setAnalysis("0");

            //user相关
            moreInfoEntity.setAddTime(new Date());
            moreInfoEntity.setAddUname(user.getAddUname());
            moreInfoEntity.setAddUid(user.getUserId());
            moreInfoEntity.setUserId(user.getUserId());

            //1代表公积金
            moreInfoEntity.setDataType("6");
            moreInfoEntity.setGetdataMaxTimes(MAXTIMES);

            flag = true;
        }

        //开始登录
        String fengchao_gongjijing = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_GETPROVIDENTFUNDINFO);
        JSONObject fgJson = JSON.parseObject(fengchao_gongjijing);
        JSONObject loginandcatchgjjaccount = fgJson.getJSONObject("fengchao_gongjijin_loginandcatchgjjaccount");
        Map<String, Object> loginParameter = gongjijingDTO.getLoginParameter();
        loginandcatchgjjaccount.put("body", loginParameter);

        log.info("开始发起公积金登录");

        String sendApiPost = requestService.sendApiPost(loginandcatchgjjaccount.toJSONString());
        log.info("登录请求结束，返回结果为："+sendApiPost);
        JSONObject accInfo = JSON.parseObject(sendApiPost);
        JSONObject head = accInfo.getJSONObject("head");
        JSONObject body = accInfo.getJSONObject("body");
        String status = body.getString("status");
        if (head==null||body==null||!"0000".equals(head.getString("responseCode"))
                || StringUtils.isBlank(status)) {
            log.error("接口平台请求异常");
            response.setResponseCode(ResponseCodeEnum.INTERFACE_ERROR);
            return response;
        }

        switch (status) {
            case "1":
                moreInfoEntity.setGetdata("1");
                if(flag){
                    moreInfoDao.insertSelective(moreInfoEntity);
                }else{
                    moreInfoEntity.setUpdateUid(user.getUserId());
                    moreInfoEntity.setUpdateUname(user.getAddUname());
                    moreInfoEntity.setUpdateTime(DateUtil.getNow());
                    moreInfoDao.updateByPrimaryKey(moreInfoEntity);
                }
                //保存登录成功的参数，然后发送到队列中去
                gongjijingDTO.setLocationCid(body.getString("location_cid"));
                gongjijingDTO.setSurnameSid(body.getString("surname_sid"));
                response.setResponseCode(ResponseCodeEnum.SUCCESSED);
                break;
            case "-5":
                log.info("token错误");
                response.setResponseCode(ResponseCodeEnum.INTERFACE_ERROR,"session_token 不存在");
                return response;
            case "105"://用户名或密码错误
            default:
                response.setResponseCode(ResponseCodeEnum.INTERFACE_ERROR,body.getString("errors"));
                return response;
        }
        //通过队列获取报告
        commonSenderService.sendMessage2Rabbitmq(QueueEnum.FENGCHAO_GONGJIJING_REPORT, gongjijingDTO);
        return response;
    }

}
